<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            /*

            封闭岛屿：即被1包裹的0，但是靠近岸边陆地的就不是，需要转换下思路，之前是让陆地变海洋，这次是海洋变陆地

            因此，我们需要把靠边的岛屿排除掉(不仅仅是靠边，还要周边的海洋和相邻的海洋都变为1)
            */
            var closedIsland = function (grid) {
                let m = grid.length
                let n = grid[0].length
                let count = 0
                function dfs(i, j) {
                    //如果是陆地了就不用考虑
                    if (i < 0 || j < 0 || i >= m || j >= n || grid[i][j] == 1) {
                        return
                    }
                    grid[i][j] = 1
                    dfs(i - 1, j)
                    dfs(i + 1, j)
                    dfs(i, j - 1)
                    dfs(i, j + 1)
                }

                //把靠边的变成陆地
                for (let i = 0; i < m; i++) {
                    for (let j = 0; j < n; j++) {
                        if (i == 0 || i == m - 1 || j == 0 || j == n - 1) {
                            if (grid[i][j] == 0) {
                                dfs(i, j)
                            }
                        }
                    }
                }
                for (let i = 0; i < m; i++) {
                    for (let j = 0; j < n; j++) {
                        if (grid[i][j] == 0) {
                            count++
                            dfs(i, j)
                        }
                    }
                }
                return count
            }
        </script>
    </body>
</html>
